<!-- 服务列表 -->
<template>
  <div class="HomePageStyle">
    <!-- // 简体 -->
    <el-descriptions v-if="HomepageTable.length > 2" style="border: #ccc 1px solid;padding: 20px;" title="简体内容"
      :column="2" size="14">
      <el-descriptions-item>{{ HomepageTable[0].content }}</el-descriptions-item>
      <template slot="extra">
        <el-button type="primary" size="small" @click="tableEditing(1)">编辑</el-button>
      </template>
    </el-descriptions>
    <!-- 英文 -->
    <el-descriptions v-if="HomepageTable.length > 2" style="border: #ccc 1px solid;padding: 20px;" title="英文内容"
      :column="2" size="">
      <el-descriptions-item label="繁体内容">{{ HomepageTable[1].en_content }}</el-descriptions-item>
      <template slot="extra">
        <el-button type="primary" size="small" @click="tableEditing(2)">编辑</el-button>
      </template>
    </el-descriptions>
    <!-- 繁体 -->
    <el-descriptions v-if="HomepageTable.length > 2" style="border: #ccc 1px solid;padding: 20px;" title="繁体内容"
      :column="2" size="">
      <el-descriptions-item label="内容">{{ HomepageTable[2].tw_content }}</el-descriptions-item>

      <template slot="extra">
        <el-button type="primary" size="small" @click="tableEditing(3)">编辑</el-button>
      </template>
    </el-descriptions>
    <!-- 弹窗 -->
    <el-dialog :title="titles" :visible.sync="dialogVisible" width="70%" @close="handleClose" top="10vh"
      :fullscreen="f11">
      <div class="pop-up-form" style="min-height: calc(100vh - 125px - 10vh);">
        <div style="width: 100%;padding: 0 0 0 4%;">
          <h3 style="flex: 2; text-align: center; line-height: 40px; font-weight: 700; font-size: 15px;width: 100%;">内容：
          </h3>
          <div style="border: 1px solid #ccc;height:auto">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
            <Editor style="height: calc(100vh - 120px - 10vh - 125px); overflow-y: hidden;" v-model="html"
              :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" @onChange="onChange"
              @onDestroyed="onDestroyed" @onMaxLength="onMaxLength" @onFocus="onFocus" @onBlur="onBlur"
              @customAlert="customAlert" @customPaste="customPaste" />
          </div>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="upd_updateServiceContent()" size="small">更 新</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { obtainServiceContent, updateServiceContent } from "@/utils/api";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// import { DomEditor } from "@wangeditor/editor";
export default {
  name: 'BrokerInfo',
  components: { Editor, Toolbar },
  data() {
    return {
      // 富文本
      editor: null, // 富文本实例对象
      html: '<p>hello</p>', // 富文本初始html
      toolbarConfig: {
        excludeKeys: [
          // 'group-image',
          'group-video'
        ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: '/admin/Upload/upload', // 上传图片的地址
            fieldName: 'image', // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              'token': localStorage.getItem('token'), // 将 token 添加在请求头中
            },
            allowedFileTypes: ['image/*'], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log('图片上传成功', res, file);
              alert(res.msg)
            },
            onFailed(file, res) {
              console.log(res, file, '失败');
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert(res, insertFn) {
              // 从服务端响应中获取图片 URL
              const imageUrl =  res.data[0]; // 根据服务器响应结构修改
              // 使用 insertFn 插入图片
              insertFn(imageUrl);
              console.log(insertFn, 'insertFn');
            },
          }
        },

      },// 富文本提示
      mode: 'default', // or 'simple'
      // 新增编辑表单
      addform: {
        body_html: '',
      },
      HomepageTable: [],//表格
      dialogVisible: false,//弹窗
      titles: '', // 弹窗标题、按钮判断
      f11: false,
      roleHeadgear: null,

      dquid: null
    };
  },
  created() {
    this.get_obtainServiceContent()
  },
  mounted() {

  },
  methods: {
    // 查询主页列表
    async get_obtainServiceContent() {
      let data = {
        menu_id: 11
      }

      const res = await obtainServiceContent(data).catch((err) => {
        return console.error(err);
      });
      if (res.data.code == "200") {
        // this.$message.success(res.data.msg);
        const dataArray = [];
        for (let i = 0; i < 3; i++) {
          dataArray.push({ ...res.data.data, uid: i + 1 });
        }

        this.HomepageTable = dataArray
        console.log(this.HomepageTable, 'resres11111111111');
      } else {
        this.$message.error(res.data.msg);
      }
    },
    // 更新主页
    async upd_updateServiceContent() {
      let data = new FormData();
      data.append('menu_id', 11);

      switch (this.dquid) {
        case 1:
          data.append('content', this.editor.getHtml());
          break;
        case 2:
          data.append('en_content', this.editor.getHtml());
          break;
        case 3:
          data.append('tw_content', this.editor.getHtml());
          break;
        default:
        // contentToSet = ''; // 如果没有匹配的，设置为默认值或空字符串
      }
      const res = await updateServiceContent(data).catch((err) => {
        return console.error(err);
      });
      if (res.data && res.data.code == "200") {
        this.$message.success(res.data.msg);
        this.dialogVisible = false
        this.get_obtainServiceContent()
      } else {
        this.$message.error(res.data.msg);
      }
    },
    // 关闭弹窗时
    handleClose() {
      this.addform = {
        body_html: '',
      }
    },
    // 分页
    current_change(currentPage) {
      this.currentPage = currentPage;
      this.get_obtainServiceContent();
    },
    // 编辑打开时
    tableEditing(uid) {
      this.dquid = uid
      this.titles = '编辑';
      this.dialogVisible = true;

      setTimeout(() => {
        // 根据 uid 筛选出对应的数组项
        const selectedItem = this.HomepageTable.find(item => item.uid === uid);

        if (selectedItem) {
          let contentToSet;

          // 根据 uid 选择相应的内容
          if (uid === 1) {
            contentToSet = selectedItem.content;
          } else if (uid === 2) {
            contentToSet = selectedItem.en_content;
          } else if (uid === 3) {
            contentToSet = selectedItem.tw_content;
          }

          // 设置富文本内容
          this.editor.setHtml(contentToSet);
        }
      }, 500);
    },
    // 富文本
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    // 组件销毁时销毁编辑器
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy()
    },
    onChange(editor) {
      console.log(editor, this.editor, '121212121')
    },
    onDestroyed(editor) { console.log('onDestroyed', editor) },
    onMaxLength(editor) { console.log('onMaxLength', editor) },
    onFocus(editor) { console.log('onFocus', editor) },
    onBlur(editor) { console.log('onBlur', editor) },
    customAlert(info, type) { window.alert(`customAlert in Vue demo\n${type}:\n${info}`) },
    customPaste(editor, event, callback) {
      console.log('ClipboardEvent 粘贴事件对象', event)
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 自定义插入内容
      // editor.insertText('xxx')

      // 返回 false ，阻止默认粘贴行为
      // event.preventDefault()
      // callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）

      // 返回 true ，继续默认的粘贴行为
      // callback(true)
      console.log(editor, event, callback);
    },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.el-dialog__body {
  padding: 0 10px;
}
</style>
<style lang="less" scoped>
.HomePageStyle {
  width: 100%;
  padding: 0 10px;
  // background-color: aquamarine;
  height: calc(100vh - 100px);
  // border: 1px #000 solid;

  .cardAdmin {
    position: relative;
    // height: 18%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 0;

    border: #ebeef5 solid 1px;
    padding: 0 5px;
    margin-bottom: 2px;


    .formContainer {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      padding-bottom: 40px !important;
      padding: 0;
      align-self: baseline;
    }

    .formSearch {
      width: 25%;
      min-width: 25%;
      margin: 10px 0;
      height: 40px;
      display: flex;
      justify-content: center;
    }
  }

  .pop-up-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 0;
    align-self: baseline;
    margin: 10px 0;
    justify-content: center;
    padding-right: 15px;
    height: auto;

    .form-options {
      width: 100%;
      min-width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }
}

.w-e-text-container {
  position: fixed;
}
</style>
